// 修改 ImageManager.java 文件
package util;

import cn.hutool.core.io.FileUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.io.File;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;

import static util.GUIUtil.createButton;

public class ImageManager {


    public static JPanel createImagePanel(File folder, Color backgroundColor) {
        JPanel mainPanel = new JPanel(new BorderLayout());
        mainPanel.setBackground(backgroundColor);
        // 添加操作按钮
        JPanel buttonPanel = getButtonPanel(mainPanel, folder);
        buttonPanel.setBackground(backgroundColor);
        mainPanel.add(buttonPanel, BorderLayout.NORTH);

        List<File> images = listImages(folder);
        if (images.isEmpty()) {
            JLabel emptyLabel = new JLabel("该用户未添加图片！", SwingConstants.CENTER);
            mainPanel.add(emptyLabel, BorderLayout.CENTER);
            emptyLabel.setBackground(backgroundColor);
            return mainPanel;
        }

        /* ---------- 网格缩略图面板（每行最多4张） ---------- */
        JPanel flowPanel = new JPanel(new GridLayout(0, 4, 10, 10));
        flowPanel.setBackground(backgroundColor);
        List<ThumbnailLabel> labels = new ArrayList<>();
        for (File img : images) {
            ThumbnailLabel lbl = new ThumbnailLabel(img);
            labels.add(lbl);
            flowPanel.add(lbl);
        }

        /* ---------- 预览窗口（单例） ---------- */
        JDialog previewDialog = new JDialog(SwingUtilities.getWindowAncestor(mainPanel), "预览", Dialog.ModalityType.MODELESS);
        previewDialog.setDefaultCloseOperation(JDialog.HIDE_ON_CLOSE);
        JLabel previewLabel = new JLabel("", SwingConstants.CENTER);
        previewDialog.add(new JScrollPane(previewLabel));

        // 将键盘监听器封装为方法，方便刷新时重新注册
        registerKeyListener(labels, previewLabel, previewDialog);

        mainPanel.add(new JScrollPane(flowPanel), BorderLayout.CENTER);


        return mainPanel;
    }

    private static void registerKeyListener(List<ThumbnailLabel> labels,
                                            JLabel previewLabel, JDialog previewDialog) {
        KeyboardFocusManager.getCurrentKeyboardFocusManager()
                .addKeyEventDispatcher(e -> {
                    if (e.getID() == KeyEvent.KEY_PRESSED) {
                        if (e.getKeyCode() == KeyEvent.VK_SPACE) {
                            List<ThumbnailLabel> sel = getSelected(labels);
                            if (sel.size() != 1) return false;

                            if (!previewDialog.isVisible()) {
                                showPreview(sel.getFirst().imgFile, previewLabel, previewDialog);
                            } else {
                                previewDialog.setVisible(false);
                            }
                            return true;
                        }
                        // 添加 Delete 键监听
                        else if (e.getKeyCode() == KeyEvent.VK_DELETE) {
                            // 获取当前选中的组件
                            Component focusOwner = KeyboardFocusManager.getCurrentKeyboardFocusManager().getFocusOwner();
                            if (focusOwner != null) {
                                // 查找包含图片的主面板
                                JPanel mainPanel = findMainPanel(focusOwner);
                                if (mainPanel != null) {
                                    // 获取文件夹路径
                                    File folder = findFolderFromPanel();
                                    deleteImage(mainPanel, folder);
                                    return true;
                                }
                            }
                        }
                    }
                    return false;
                });
    }

    private static JPanel findMainPanel(Component component) {
        while (component != null) {
            if (component instanceof JPanel && ((JPanel) component).getLayout() instanceof BorderLayout) {
                // 检查是否包含滚动面板（图片区域）
                for (Component child : ((JPanel) component).getComponents()) {
                    if (child instanceof JScrollPane) {
                        return (JPanel) component;
                    }
                }
            }
            component = component.getParent();
        }
        return null;
    }

    // 添加辅助方法从面板获取文件夹路径
    private static File findFolderFromPanel() {
        // 这里需要根据实际业务逻辑获取文件夹路径
        // 可以通过 UserManager 获取当前用户的图片目录
        String username = UserManager.getOnlineUser().getUsername();
        String basePath = JsonRW.getStr(JsonRW.configFile, "userDataDir") + "/" + username + "/images";
        return new File(basePath);
    }


    private static JPanel getButtonPanel(JPanel mainPanel, File folder) {
        JPanel buttonPanel = new JPanel(new FlowLayout(FlowLayout.LEFT));
        // 可配置的按钮列表
        JButton[] buttons = {
                createButton("添加图片", _ -> addImage(mainPanel, folder)),
                createButton("删除图片", _ -> deleteImage(mainPanel, folder))
        };

        for (JButton button : buttons) {
            buttonPanel.add(button);
        }
        return buttonPanel;
    }

    private static void refresh(JPanel panel, File folder) {
        panel.removeAll();
        JPanel newPanel = createImagePanel(folder, new Color(240, 240, 240));
        panel.add(newPanel, BorderLayout.CENTER);
        panel.revalidate();
        panel.repaint();
    }

    private static void addImage(JPanel mainPanel, File folder) {
        System.out.println("添加图片");
        GUIUtil.showFileSelectionDialog(null, "选择一张图片（尽量是方形的）", filePath -> {
            UserManager.addImage(UserManager.getOnlineUser().getUsername(), filePath);
            JOptionPane.showMessageDialog(null, "添加成功！");
        });
        refresh(mainPanel, folder);
    }

    @SuppressWarnings("all")
    private static void deleteImage(JPanel mainPanel, File folder) {

        // 正确获取包含缩略图的面板
        JPanel thumbnailPanel = findThumbnailPanel(mainPanel);

        if (thumbnailPanel == null) {
            JOptionPane.showMessageDialog(mainPanel, "无法找到图片面板！", "错误", JOptionPane.ERROR_MESSAGE);
            return;
        }

        // 获取所有缩略图组件
        Component[] components = thumbnailPanel.getComponents();
        List<ThumbnailLabel> thumbnailLabels = new ArrayList<>();

        for (Component component : components) {
            if (component instanceof ThumbnailLabel) {
                thumbnailLabels.add((ThumbnailLabel) component);
            }
        }

        // 获取选中的图片
        List<ThumbnailLabel> selectedLabels = getSelected(thumbnailLabels);

        if (selectedLabels.isEmpty()) {
            JOptionPane.showMessageDialog(mainPanel, "请先选择要删除的图片！", "提示", JOptionPane.WARNING_MESSAGE);
            return;
        }

        int result = JOptionPane.showConfirmDialog(
                mainPanel,
                "确定要删除选中的 " + selectedLabels.size() + " 张图片吗？",
                "确认",
                JOptionPane.YES_NO_OPTION
        );

        if (result == JOptionPane.YES_OPTION) {
            try {
                // 删除选中的图片文件
                for (ThumbnailLabel label : selectedLabels) {
                    File imageFile = label.imgFile;
                    if (imageFile.exists()) {
                        boolean deleteStatus = imageFile.delete();
                        if (!deleteStatus) {
                            throw new RuntimeException("删除文件失败！");
                        }
                    }
                }

                // 重新序列化剩余图片名称
                sequenceImages(folder);

                // 刷新界面
                refresh(mainPanel, folder);

                JOptionPane.showMessageDialog(mainPanel, "删除成功！", "提示", JOptionPane.INFORMATION_MESSAGE);
            } catch (Exception ex) {
                JOptionPane.showMessageDialog(mainPanel, "删除图片时发生错误：" + ex.getMessage(), "错误", JOptionPane.ERROR_MESSAGE);
                ex.printStackTrace();
            }
        }
        reFormat();
    }

    private static JPanel findThumbnailPanel(JPanel mainPanel) {
        // 遍历主面板的组件
        for (Component component : mainPanel.getComponents()) {
            if (component instanceof JScrollPane scrollPane) {
                // 获取视口中的组件
                Component viewComponent = scrollPane.getViewport().getView();
                if (viewComponent instanceof JPanel) {
                    return (JPanel) viewComponent;
                }
            }
        }
        return null;
    }


    private static void sequenceImages(File folder) {
        List<File> imageFiles = listImages(folder);

        // 按名称排序，确保按顺序重命名
        imageFiles.sort((f1, f2) -> {
            String name1 = f1.getName();
            String name2 = f2.getName();
            return name1.compareTo(name2);
        });

        // 获取支持的图片类型
        HashSet<String> imageTypeSupport = JsonRW.getStringSet(JsonRW.configFile, "imageTypeSupport");

        // 重新命名文件
        for (int i = 0; i < imageFiles.size(); i++) {
            File oldFile = imageFiles.get(i);
            String extension = getFileExtension(oldFile);

            // 如果无法获取扩展名或不支持的格式，跳过
            if (extension == null || !imageTypeSupport.contains(extension.toUpperCase())) {
                continue;
            }

            File newFile = new File(folder, (i + 1) + "." + extension);

            // 如果文件名已经正确，跳过
            if (oldFile.getAbsolutePath().equals(newFile.getAbsolutePath())) {
                continue;
            }

            // 重命名文件
            boolean renameStatus = oldFile.renameTo(newFile);
            if (!renameStatus) {
                System.out.println("重命名失败：" + oldFile.getAbsolutePath());
            }
        }
    }

    private static String getFileExtension(File file) {
        String name = file.getName();
        int lastDotIndex = name.lastIndexOf('.');
        if (lastDotIndex > 0) {
            return name.substring(lastDotIndex + 1);
        }
        return null;
    }


    /* ---------------------------- 工具方法 ---------------------------- */

    private static List<File> listImages(File folder) {
        List<File> list = new ArrayList<>();
        File[] fs = folder.listFiles();
        if (fs == null) return list;
        for (File f : fs) {
            String n = f.getName().toLowerCase();
            if (n.endsWith(".jpg") || n.endsWith(".jpeg") || n.endsWith(".png")
                    || n.endsWith(".gif") || n.endsWith(".bmp")) list.add(f);
        }
        return list;
    }

    private static List<ThumbnailLabel> getSelected(List<ThumbnailLabel> labels) {
        List<ThumbnailLabel> sel = new ArrayList<>();
        for (ThumbnailLabel lbl : labels) if (lbl.selected) sel.add(lbl);
        return sel;
    }

    private static void showPreview(File imgFile, JLabel label, JDialog dialog) {
        ImageIcon src = new ImageIcon(imgFile.getAbsolutePath());
        Image img = src.getImage();

        Dimension screen = Toolkit.getDefaultToolkit().getScreenSize();
        int maxW = (int) (screen.width * 0.9);
        int maxH = (int) (screen.height * 0.9);

        int w = img.getWidth(null);
        int h = img.getHeight(null);

        if (w > maxW || h > maxH) {
            double scale = Math.min(1.0 * maxW / w, 1.0 * maxH / h);
            w = (int) (w * scale);
            h = (int) (h * scale);
        }

        Image scaled = img.getScaledInstance(w, h, Image.SCALE_SMOOTH);
        label.setIcon(new ImageIcon(scaled));
        dialog.setTitle("预览 - " + imgFile.getName() + "（按下空格关闭）");
        dialog.setSize(w + 20, h + 40);
        dialog.setLocationRelativeTo(null);

        dialog.setModal(true);
        dialog.setVisible(true);
    }

    /* ---------------------------- 缩略图组件 ---------------------------- */

    private static class ThumbnailLabel extends JLabel {
        private static final int SIZE = 150;
        private final File imgFile;
        private boolean selected = false;

        ThumbnailLabel(File imgFile) {
            super();
            this.imgFile = imgFile;
            setPreferredSize(new Dimension(SIZE, SIZE));
            setHorizontalAlignment(CENTER);
            setVerticalAlignment(CENTER);
            setOpaque(true);
            setBackground(new Color(240, 240, 240));

            try {
                ImageIcon icon = new ImageIcon(imgFile.getAbsolutePath());
                Image scaled = icon.getImage()
                        .getScaledInstance(SIZE, SIZE, Image.SCALE_SMOOTH);
                setIcon(new ImageIcon(scaled));
            } catch (Exception e) {
                setText("无法加载图片");
                setHorizontalAlignment(SwingConstants.CENTER);
            }

            addMouseListener(new MouseAdapter() {
                @Override
                public void mouseClicked(MouseEvent e) {
                    int index = getIndex();
                    List<ThumbnailLabel> all = getAllSiblings();

                    if (SwingUtilities.isLeftMouseButton(e)) {
                        if (e.isControlDown()) {
                            // Ctrl+单击：切换单张
                            setSelected(!selected);
                        } else if (e.isShiftDown()) {
                            // Shift+单击：区间选择
                            int lastSel = lastSelectedIndex(all);
                            if (lastSel != -1) {
                                int from = Math.min(lastSel, index);
                                int to   = Math.max(lastSel, index);
                                clearAllSelection(all);
                                for (int i = from; i <= to; i++) all.get(i).setSelected(true);
                            } else {
                                clearAllSelection(all);
                                setSelected(true);
                            }
                        } else {
                            // 普通单击：单选
                            clearAllSelection(all);
                            setSelected(true);
                        }
                    }
                }
            });
        }

        /* ------------------- 选择逻辑辅助 ------------------- */

        private List<ThumbnailLabel> getAllSiblings() {
            Component[] comps = getParent().getComponents();
            List<ThumbnailLabel> list = new ArrayList<>();
            for (Component c : comps) if (c instanceof ThumbnailLabel) list.add((ThumbnailLabel) c);
            return list;
        }

        private int getIndex() {
            return getAllSiblings().indexOf(this);
        }

        private static int lastSelectedIndex(List<ThumbnailLabel> list) {
            for (int i = list.size() - 1; i >= 0; i--)
                if (list.get(i).selected) return i;
            return -1;
        }

        private static void clearAllSelection(List<ThumbnailLabel> list) {
            for (ThumbnailLabel lbl : list) lbl.setSelected(false);
        }

        private void setSelected(boolean b) {
            selected = b;
            setBorder(selected
                    ? BorderFactory.createLineBorder(Color.RED, 3)
                    : BorderFactory.createEmptyBorder());
        }
    }

    private static void reFormat() {
        String basePath = JsonRW.getStr(JsonRW.configFile, "userDataDir") + "/" + UserManager.getOnlineUser().getUsername() + "/images";
        File baseDir = new File(basePath);
        if (!baseDir.exists()) {
            return;
        }

        File[] files = baseDir.listFiles();
        if (files == null) {
            return;
        }
        int count = 0;
        for (File file : files) {
            String fileExtension = getFileExtension(file);
            if (fileExtension == null || !JsonRW.getStringSet(JsonRW.configFile, "imageTypeSupport").contains(fileExtension)) {
                boolean deleteStatus = file.delete();
                if (!deleteStatus) {
                    throw new RuntimeException("文件删除失败");
                }
                continue;
            }
            count++;
            FileUtil.rename(file, count + "." + fileExtension, false);
        }
    }
}
